package org.gwt.project.tools;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.wst.common.project.facet.core.IDelegate;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;

public class ToolsUnInstall extends WorkspaceJob implements IDelegate {

	private IProject project;
	
	@SuppressWarnings("unused")
	private ToolsConfig config;

	public ToolsUnInstall() {
		super("");
	}

	public ToolsUnInstall(IProject project, ToolsConfig config) {
		super("");
		this.config = config;
		this.project = project;
	}
	
	public void configure(IProject project, ToolsConfig config) throws CoreException {

		// Cache references
		this.config = config;
		this.project = project;
		
		// Update name
		setName("Uninstalling facet from [" + project.getName() + "]");

		// Create scheduling rule for all projects associated with project.
		setRule(ToolsUtil.modifyAll(project));

		// Forward
		schedule();
		
	}

	@Override
	public void execute(IProject project, IProjectFacetVersion version,
			Object config, IProgressMonitor monitor) throws CoreException {

		// Forward
		uninstallNature(project, monitor);

	}
	
	@Override
	public IStatus runInWorkspace(IProgressMonitor monitor) {
		try {

			// Forward
			uninstallNature(project, monitor);

			// Finished
			return ToolsPlugin.asOK("Facet uninstalled");

		} catch (CoreException e) {
			// Failed
			return ToolsPlugin.asERROR("Facet not uninstalled", e);

		}
	}
	
	
	public static void uninstallNature(
			IProject project, IProgressMonitor monitor) throws CoreException {
		
		// Collect current set of natures
		IProjectDescription description = project.getDescription();
		
		// Only install once
		if (!description.hasNature(ToolsNature.ID)) return;
		
		// Remove nature 
		String[] natures = description.getNatureIds();
		for (int i = 0; i < natures.length; ++i) {
			if (ToolsNature.ID.equals(natures[i])) {
				// Remove the nature
				String[] newNatures = new String[natures.length - 1];
				System.arraycopy(natures, 0, newNatures, 0, i);
				System.arraycopy(natures, i + 1, newNatures, i,
						natures.length - i - 1);
				description.setNatureIds(newNatures);
				project.setDescription(description, null);
				return;
			}
		}		
	}

}
